# 迷宫细化
import pygame
import sys
import random

# 初始化Pygame
pygame.init()

# 设置窗口大小
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

# 设置标题
pygame.display.set_caption("迷宫逃脱游戏")

# 定义颜色
black = (0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
red = (255, 0, 0)
blue = (0, 0, 255)

# 迷宫参数
maze_width = 20
maze_height = 20
cell_size = 30


# 生成迷宫
class Maze:
    def __init__(self, width, height):
        self.width = width
        self.height = height
        self.grid = [[Cell(x, y) for y in range(height)] for x in range(width)]

    def generate(self):
        start_x = random.randint(0, self.width - 1)
        start_y = random.randint(0, self.height - 1)
        self.grid[start_x][start_y].visited = True
        stack = [(start_x, start_y)]

        while stack:
            (cx, cy) = stack[-1]
            neighbors = self.get_neighbors(cx, cy)
            if len(neighbors) > 0:
                nx, ny = random.choice(neighbors)
                self.grid[cx][cy].remove_walls(nx, ny, self.grid)
                self.grid[nx][ny].visited = True
                stack.append((nx, ny))
            else:
                stack.pop()

    def get_neighbors(self, cx, cy):
        neighbors = []
        for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            nx, ny = cx + dx, cy + dy
            if 0 <= nx < self.width and 0 <= ny < self.height and not self.grid[nx][ny].visited:
                neighbors.append((nx, ny))
        return neighbors


class Cell:
    def __init__(self, x, y):
        self.x, self.y = x, y
        self.walls = [True, True, True, True]  # up, right, down, left
        self.visited = False

    def remove_walls(self, nx, ny, grid):
        dx = nx - self.x
        dy = ny - self.y
        if dx == 1:
            self.walls[1] = False
            grid[nx][ny].walls[3] = False
        elif dx == -1:
            self.walls[3] = False
            grid[nx][ny].walls[1] = False
        elif dy == 1:
            self.walls[2] = False
            grid[nx][ny].walls[0] = False
        elif dy == -1:
            self.walls[0] = False
            grid[nx][ny].walls[2] = False


# 游戏状态
class GameState:
    def __init__(self):
        self.maze = Maze(maze_width, maze_height)
        self.maze.generate()
        self.player = {'x': 1, 'y': 1}
        self.exit_point = {'x': maze_width - 2, 'y': maze_height - 2}
        self.state = 'playing'

    def update(self):
        if self.state == 'playing':
            self.move_player()
            self.check_victory()

    def move_player(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.move(-1, 0)
        elif keys[pygame.K_RIGHT]:
            self.move(1, 0)
        elif keys[pygame.K_UP]:
            self.move(0, -1)
        elif keys[pygame.K_DOWN]:
            self.move(0, 1)

    def move(self, dx, dy):
        new_x = self.player['x'] + dx
        new_y = self.player['y'] + dy
        if 0 <= new_x < maze_width and 0 <= new_y < maze_height:
            cell = self.maze.grid[new_x][new_y]
            if not cell.walls[(dx + dy) % 2]:  # Check if the wall is open
                self.player['x'] = new_x
                self.player['y'] = new_y

    def check_victory(self):
        if self.player['x'] == self.exit_point['x'] and self.player['y'] == self.exit_point['y']:
            self.state = 'won'
            print("恭喜你找到了出口！")

    def draw(self):
        screen.fill(black)
        for row in self.maze.grid:
            for cell in row:
                x = cell.x * cell_size
                y = cell.y * cell_size
                if cell.walls[0]:
                    pygame.draw.line(screen, white, (x, y), (x + cell_size, y))
                if cell.walls[1]:
                    pygame.draw.line(screen, white, (x + cell_size, y), (x + cell_size, y + cell_size))
                if cell.walls[2]:
                    pygame.draw.line(screen, white, (x + cell_size, y + cell_size), (x, y + cell_size))
                if cell.walls[3]:
                    pygame.draw.line(screen, white, (x, y + cell_size), (x, y))

        # 绘制玩家
        pygame.draw.rect(screen, green,
                         (self.player['x'] * cell_size, self.player['y'] * cell_size, cell_size, cell_size))

        # 绘制出口
        pygame.draw.rect(screen, red,
                         (self.exit_point['x'] * cell_size, self.exit_point['y'] * cell_size, cell_size, cell_size))


# 游戏主循环
state = GameState()
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    state.update()

    state.draw()

    pygame.display.flip()

    # 控制游戏帧率
    pygame.time.delay(100)

# 清理并退出Pygame
pygame.quit()
sys.exit()